<template>
  <div>
    <!-- 房间选择对话框 -->
    <el-dialog
      title="选择入住房间"
      :visible.sync="roomSelectDialogVisible"
      width="1300px"
      class="room-select-dialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      top="5vh"
    >
      <el-row :gutter="24">
        <el-col :span="14">
          <div class="room-selection-section">

            <!-- 搜索条件区域 -->
            <div class="search-conditions">
              <el-form :model="roomSearchForm" :inline="true" size="small">
                <el-form-item label="房屋类型">
                  <el-select v-model="roomSearchForm.roomTypeId" placeholder="请选择房屋类型" clearable @change="handleSearchChange">
                    <el-option
                      v-for="dict in dict.type.home_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="校区">
                  <el-select v-model="roomSearchForm.cellId" placeholder="请选择校区"  @change="handleCellChange">
                    <el-option v-for="item in cellOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="楼栋">
                  <el-select
                    v-model="roomSearchForm.unitId"
                    placeholder="请选择楼栋"
                    :disabled="!roomSearchForm.cellId"
                    @change="handleUnitChange"
                    filterable
                  >
                    <el-option v-for="item in unitOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="楼层">
                  <el-select
                    v-model="roomSearchForm.floorId"
                    placeholder="请选择楼层"
                    clearable
                    :disabled="!roomSearchForm.unitId"
                    @change="handleSearchChange"
                    filterable
                  >
                    <el-option v-for="item in floorOptions" :key="item.id" :label="item.floorName" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="el-icon-search" @click="searchRooms">搜索</el-button>
                  <el-button icon="el-icon-refresh" @click="resetRoomSearch">重置</el-button>
                </el-form-item>
              </el-form>
            </div>

            <div class="transfer-container">
              <el-transfer
                v-model="selectedRoomIds"
                :data="getTransferData()"
                filterable
                filter-placeholder="输入房间号搜索"
                :titles="['可选房间', '已选择房间']"
                :props="{key: 'id', label: 'roomName'}"
                :filter-method="filterRooms"
                class="custom-transfer"
                :left-default-checked="[]"
                :right-default-checked="[]"
                :render-content="renderContent"
                @change="handleTransferChange"
              />
            </div>
          </div>
        </el-col>
        <el-col :span="10">
          <div class="time-setting-section" :class="{ 'time-section-active': selectedRoomIds.length > 0 }">
            <div class="section-header">
              <h4>入住时间设置</h4>
              <div class="section-tip">为选中的房间设置入住时间</div>
            </div>
            <div v-if="selectedRoomIds.length > 0" class="time-content">
              <el-form ref="roomTimeForm" :model="roomTimeForm" :rules="roomTimeRules" label-width="80px" class="time-form">
                <el-form-item label="入住时间" prop="startTime">
                  <el-date-picker
                    v-model="roomTimeForm.startTime"
                    type="datetime"
                    placeholder="选择入住开始时间"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    style="width: 100%"
					:popper-class="'currentDatePickerClass'"
				  
                    prefix-icon="el-icon-date"
                    @change="onRoomStartTimeChange"
                  />
                </el-form-item>
                <el-form-item label="离开时间" prop="endTime">
                                      <el-date-picker
                      v-model="roomTimeForm.endTime"
                      type="datetime"
                      placeholder="选择时间"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      style="width: 100%"
                      prefix-icon="el-icon-date"
					  :popper-class="'currentDatePickerClass'"
                      :picker-options="{
                        disabledDate: time => {
                          if (roomTimeForm.startTime) {
                            return time.getTime() <= new Date(roomTimeForm.startTime).getTime();
                          }
                          return false;
                        }
                      }"
                    />
                </el-form-item>
              </el-form>
            </div>
            <div v-else class="time-placeholder">
              <i class="el-icon-time"></i>
              <p>请先选择要入住的房间</p>
            </div>
          </div>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelRoomSelect">取消</el-button>
        <el-button type="primary" @click="confirmRoomSelect" :disabled="!canConfirmRoomSelect">
          {{ selectedRoomIds.length > 1 ? `入住 ${selectedRoomIds.length} 个房间` : '确认入住' }}
        </el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
  import {
    batchRuzhu
  } from "@/api/lock/tenantUser";
  import {
    getHomeListByUserIdruzhu
  } from "@/api/lock/home";
  import {
    listCell2
  } from "@/api/lock/cell";
  import {
    listUnit2
  } from "@/api/lock/unit";
  import {
    listFloor2
  } from "@/api/lock/floor";



  export default {
    name: "Ruzhu",
    dicts: ['home_type'],
    data() {
      return {
        tenantInfo:{},
        // 房间选择相关数据
        roomSelectDialogVisible: false,
        selectedRoomIds: [],
        availableRoomList: [],
        allSelectedRooms: [], // 存储所有已选择的房间完整信息
        roomTimeForm: {
          startTime: '',
          endTime: ''
        },
        roomTimeRules: {
          startTime: [{
            required: true,
            message: '请选择开始时间',
            trigger: 'blur'
          }],
          endTime: [{
            required: true,
            message: '请选择结束时间',
            trigger: 'blur'
          }, {
            validator: (rule, value, callback) => {
              if (value && this.roomTimeForm.startTime) {
                const startTime = new Date(this.roomTimeForm.startTime).getTime();
                const endTime = new Date(value).getTime();
                if (endTime <= startTime) {
                  callback(new Error('离开时间必须大于入住时间'));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: 'change'
          }]
        },
        // 房间搜索表单
        roomSearchForm: {
          roomTypeId: null,
          cellId: null,
          unitId: null,
          floorId: null
        },
        // 选项数据
        cellOptions: [],
        unitOptions: [],
        floorOptions: []
      };
    },
    computed: {
      canConfirmRoomSelect() {
        return this.selectedRoomIds.length > 0 &&
               this.roomTimeForm.startTime &&
               this.roomTimeForm.endTime;
      }
    },
    created() {
      // 不再需要手动获取关系字典数据
    },
    methods: {
      // 显示入住对话框
      showDialog(tenantInfo) {
        this.tenantInfo = tenantInfo;
        // 显示房间选择对话框
        this.showRoomSelectDialog();
      },



      // 显示房间选择对话框
      async showRoomSelectDialog() {
        this.roomSelectDialogVisible = true;
        // 先加载选项并等待默认选择完成
        await this.loadOptions();
        // 然后根据默认选择的校区和楼栋加载房间列表
        this.loadAvailableRooms();
      },

            // 加载可用房间列表
      async loadAvailableRooms() {
        try {
          // 构建搜索参数
          const searchParams = {
            userId: this.tenantInfo.id
          };

          // 添加房屋类型搜索条件
          if (this.roomSearchForm.roomTypeId) {
            searchParams.roomTypeId = this.roomSearchForm.roomTypeId;
          }

          // 添加校区搜索条件
          if (this.roomSearchForm.cellId) {
            searchParams.cellId = this.roomSearchForm.cellId;
          }

          // 添加楼栋搜索条件
          if (this.roomSearchForm.unitId) {
            searchParams.unitId = this.roomSearchForm.unitId;
          }

          // 添加楼层搜索条件
          if (this.roomSearchForm.floorId) {
            searchParams.floorId = this.roomSearchForm.floorId;
          }

          // 调用API获取用户未入住的房间列表
          const response = await getHomeListByUserIdruzhu(searchParams);

          if (response.rows) {
            this.availableRoomList = response.rows.map(room => {
              const roomName = `${room.floorName}-${room.roomName}`;

              return {
                ...room,
                id: room.id,
                roomName: roomName
              };
            });
          }
        } catch (error) {
          console.error('加载房间列表失败:', error);
          this.$message.error('加载房间列表失败');
        }
      },

      // 取消房间选择
      cancelRoomSelect() {
        this.roomSelectDialogVisible = false;
        this.selectedRoomIds = [];
        this.allSelectedRooms = [];
        this.roomTimeForm = {
          startTime: '',
          endTime: ''
        };
      },

      // 确认房间选择
      confirmRoomSelect() {
        this.$refs.roomTimeForm.validate(valid => {
          if (valid) {
            // 执行批量入住
            this.executeBatchRuzhu().then(() => {
              // 入住成功后，关闭房间选择对话框
              this.roomSelectDialogVisible = false;

              // 清理选中的房间信息
              this.selectedRoomIds = [];
              this.allSelectedRooms = [];
              this.availableRoomList = [];

              // 重置时间表单
              this.roomTimeForm = {
                startTime: '',
                endTime: ''
              };

              // 触发父组件刷新
              this.$emit('refresh');
            }).catch(error => {
              console.error('批量入住失败:', error);
              this.$message.error('批量入住失败，请重试');
            });
          }
        });
      },

      // 执行批量入住
      async executeBatchRuzhu() {
        try {
          const batchData = {
            userId: this.tenantInfo.id,
            roomIds: this.selectedRoomIds,
            startTime: this.roomTimeForm.startTime,
            endTime: this.roomTimeForm.endTime
          };

          const response = await batchRuzhu(batchData);
          if (response.code === 200) {
            this.$message.success(response.msg || '批量入住成功');
            // 触发父组件刷新
            this.$emit('refresh');
          } else {
            throw new Error(response.msg || '批量入住失败');
          }
        } catch (error) {
          console.error('批量入住失败:', error);
          throw error;
        }
      },



      // 加载选项数据
      async loadOptions() {
        try {
          // 加载校区选项
          const cellResponse = await listCell2();
          if (cellResponse.rows && cellResponse.rows.length > 0) {
            this.cellOptions = cellResponse.rows;
            // 默认选择第一个校区
            this.roomSearchForm.cellId = cellResponse.rows[0].id;
            // 加载第一个校区的楼栋数据并等待完成
            await this.loadUnitsByCellId(cellResponse.rows[0].id);
          }
        } catch (error) {
          console.error('加载校区选项失败:', error);
        }
      },

      // 根据校区ID加载楼栋数据
      async loadUnitsByCellId(cellId) {
        try {
          const unitResponse = await listUnit2({ cellId: cellId });
          if (unitResponse.rows && unitResponse.rows.length > 0) {
            this.unitOptions = unitResponse.rows;
            // 默认选择第一个楼栋
            this.roomSearchForm.unitId = unitResponse.rows[0].id;
            // 加载第一个楼栋的楼层数据
            await this.loadFloorsByUnitId(unitResponse.rows[0].id);
          }
        } catch (error) {
          console.error('加载楼栋选项失败:', error);
        }
      },

      // 根据楼栋ID加载楼层数据
      async loadFloorsByUnitId(unitId) {
        try {
          const floorResponse = await listFloor2({ unitId: unitId });
          if (floorResponse.rows && floorResponse.rows.length > 0) {
            this.floorOptions = floorResponse.rows;
            // 默认选择第一个楼层
            this.roomSearchForm.floorId = floorResponse.rows[0].id;
          }
        } catch (error) {
          console.error('加载楼层选项失败:', error);
        }
      },

      // 校区变更处理
      async handleCellChange() {
        // 清空楼栋和楼层选择
        this.roomSearchForm.unitId = null;
        this.roomSearchForm.floorId = null;
        this.unitOptions = [];
        this.floorOptions = [];

        if (this.roomSearchForm.cellId) {
          await this.loadUnitsByCellId(this.roomSearchForm.cellId);
        }

        // 重新加载房间列表，保持已选择的房间
        this.loadAvailableRooms();
      },

      // 楼栋变更处理
      async handleUnitChange() {
        // 清空楼层选择
        this.roomSearchForm.floorId = null;
        this.floorOptions = [];

        if (this.roomSearchForm.unitId) {
          await this.loadFloorsByUnitId(this.roomSearchForm.unitId);
        }

        // 重新加载房间列表，保持已选择的房间
        this.loadAvailableRooms();
      },

      // 搜索条件变更处理
      handleSearchChange() {
        // 重新加载房间列表，保持已选择的房间
        this.loadAvailableRooms();
      },

      // 搜索房间
      searchRooms() {
        // 重新加载房间列表，保持已选择的房间
        this.loadAvailableRooms();
      },

      // 重置房间搜索
      async resetRoomSearch() {
        this.roomSearchForm.roomTypeId = null;
        this.roomSearchForm.cellId = null;
        this.roomSearchForm.unitId = null;
        this.roomSearchForm.floorId = null;
        this.unitOptions = [];
        this.floorOptions = [];
        this.selectedRoomIds = [];
        this.allSelectedRooms = [];

        // 重新加载选项并默认选择第一个
        await this.loadOptions();
        this.loadAvailableRooms();
      },

      // 自定义穿梭组件内容渲染
      renderContent(h, option) {
        const roomName = `${option.roomName}`;
        return h('span', roomName);
      },

      // 自定义穿梭组件搜索方法
      filterRooms(query, item) {
        return item.roomName.toLowerCase().includes(query.toLowerCase());
      },

      // 获取房间显示名称
      getRoomDisplayName(roomId) {
        const room = this.availableRoomList.find(r => r.id === roomId);
        return room ? room.roomName : `房间${roomId}`;
      },

      // 获取transfer组件的数据源，合并当前搜索结果和已选择的房间
      getTransferData() {
        // 合并当前搜索结果和所有已选择的房间
        const currentRooms = [...this.availableRoomList];
        const selectedRooms = [...this.allSelectedRooms];

        // 去重，避免重复添加
        const roomIds = new Set(currentRooms.map(room => room.id));
        selectedRooms.forEach(room => {
          if (!roomIds.has(room.id)) {
            currentRooms.push(room);
            roomIds.add(room.id);
          }
        });

        return currentRooms;
      },

      // 处理transfer组件的变化
      handleTransferChange(value, direction, movedKeys) {
        if (direction === 'right') {
          // 向右移动（选中房间），添加到allSelectedRooms
          movedKeys.forEach(key => {
            const room = this.availableRoomList.find(r => r.id === key);
            if (room && !this.allSelectedRooms.find(r => r.id === key)) {
              this.allSelectedRooms.push(room);
            }
          });
        } else if (direction === 'left') {
          // 向左移动（取消选中），从allSelectedRooms中移除
          movedKeys.forEach(key => {
            this.allSelectedRooms = this.allSelectedRooms.filter(r => r.id !== key);
          });
        }
      },

      /** 当入住时间改变时，重新验证离开时间 */
      onRoomStartTimeChange() {
        if (this.roomTimeForm.endTime) {
          this.$refs.roomTimeForm.validateField('endTime');
        }
      }
    }
  };
</script>

<style lang="scss" scoped>

  /* 房间选择对话框样式 */
  .room-select-dialog {
    .el-dialog__body {
      padding: 20px;
    }
  }

  .room-selection-section,
  .time-setting-section {
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    border-radius: 12px;
    padding: 20px;
    height: 500px;
    display: flex;
    flex-direction: column;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 25px rgba(0, 0, 0, 0.15);
    }
  }

  .time-setting-section {
    background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
    opacity: 0.7;
    transition: all 0.3s ease;

    &.time-section-active {
      opacity: 1;
      background: linear-gradient(135deg, #e8f5e8 0%, #c8e6c9 100%);
      transform: scale(1.02);
    }
  }

  .section-header {
    text-align: center;
    margin-bottom: 20px;

    h4 {
      margin: 0 0 8px 0;
      color: #2c3e50;
      font-size: 18px;
      font-weight: 600;
    }

    .section-tip {
      color: #7f8c8d;
      font-size: 13px;
      line-height: 1.4;
    }
  }

  .search-conditions {
    background: rgba(255, 255, 255, 0.8);
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .el-form {
      margin: 0;
    }

    .el-form-item {
      margin-bottom: 10px;
      margin-right: 15px;

      &:last-child {
        margin-right: 0;
      }
    }

    .el-select {
      width: 120px;
    }

    .el-button {
      margin-left: 5px;
      border-radius: 6px;
    }
  }

  .transfer-container {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 600px;
  }

  .custom-transfer {
    width: 100%;
    height: 100%;

    .el-transfer-panel {
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .el-transfer-panel__header {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      font-weight: 600;
      text-align: center;
      padding: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .el-transfer-panel__body {
      height: 350px;
    }

    .el-transfer-panel__list {
      padding: 0;
    }

    .el-transfer-panel__item {
      padding: 10px 15px;
      border-bottom: 1px solid #f0f0f0;
      transition: all 0.2s ease;

      &:hover {
        background-color: #f8f9fa;
        transform: translateX(2px);
      }

      &.is-checked {
        background-color: #e3f2fd;
        color: #1976d2;
      }
    }
  }

  .time-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  .time-form {
    .el-form-item {
      margin-bottom: 20px;

      .el-form-item__label {
        color: #2c3e50;
        font-weight: 500;
      }

      .el-date-editor {
        width: 100%;
      }
    }
  }

  .time-placeholder {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #bdc3c7;
    font-size: 14px;

    i {
      font-size: 48px;
      margin-bottom: 15px;
      opacity: 0.5;
    }

    p {
      margin: 0;
      font-weight: 500;
    }
  }

  .dialog-footer {
    text-align: right;
    padding: 15px 20px;
    border-top: 1px solid #ebeef5;
    background-color: #fafafa;

    .el-button {
      margin-left: 10px;
      border-radius: 6px;
      font-weight: 500;
    }
  }
</style>
